
var formatDoc = function (doc) {
    var data = doc.toJSON({ getters: true });
    data.id = doc._id.toString();
    delete data.createdAt;
    delete data.updatedAt;
    delete data.disable;
    delete data._id;
    delete data.disable;
    return data;
};
var formatDocs = function (docs) {
    var _array = [];
    for (let i = 0; i < docs.length; i++) {
        const item = formatDoc(docs[i]);
        _array.push(item);
    };
    return _array;
};


var _url = function (mongoose, Schema, PorjectName) {


    const ContentSchema = new Schema({
        url: { type: String, required: true },
        name: { type: String, required: true },
        disable: { type: Boolean, default: false }
    }, { timestamps: true });


    this.module = mongoose.model(PorjectName, ContentSchema, PorjectName);
};


_url.prototype.creat = function (doc, cb) {
    var data = new this.module(doc);
    // 将单行数据插入到数据库
    data.save(function (err, doc) {
        if (err) {
            cb(err.message, null);
        } else {
            cb(false, formatDoc(doc));
        };
    });
};
_url.prototype.updata = function (id, _doc, cb) {
    this.module.findById(id, function (err, doc) {
        doc.url = _doc.url;
        doc.name = _doc.name;
        doc.disable = false;
        doc.save(function (err, doc) {
            if (err) {
                cb(err.message, null);
            } else {
                cb(false, formatDoc(doc));
            };
        })
    });
};

_url.prototype.getAll = function (cb) {
    this.module.find({ disable: false }, function (err, docs) {
        if (err) {
            cb(error, null);
        } else {
            cb(false, formatDocs(docs));
        };
    });
};

_url.prototype.delete = function (id, cb) {
    // 删除单条记录
    this.module.findById(id, function (err, doc) {
        doc.disable = true;
        doc.save(function (err, doc) {
            if (err) {
                cb(err.message, null);
            } else {
                cb(false, formatDoc(doc));
            };
        })
    });
};

module.exports = _url;